
//import {BASE_URL} from '@/config/index.js' //获取请求域名
//引入方法
import RequestManager from '@/utils/requestManager.js' 

const manager = new RequestManager() //创建


const baseRequest = async (url, method, data = {}, loading = true) =>{
    let header = {}
	// 开启loading
	loading && uni.showLoading({title: 'loading'})
	// 生成唯一ID, 如果返回false 代表重复请求
	let requestId = manager.generateId(method, url, data)
	if(!requestId) {
		console.log('重复请求')
		return false
	}
    return new Promise((reslove, reject) => {
        uni.request({
            url: url,
            method: method || 'GET',
            header: header,
            timeout: 10000,
            data: data || {},
            success: (successData) => {
                const res = successData.data
				
                if(successData.statusCode == 200){
                    // 业务逻辑，自行修改
                    if(res.code == 404){
                        // clearStorageSync()
                        // useRouter('/pages/login/index', 'reLaunch')
                    }else{
                        reslove(res)
                    }
                }else{
                    
                    reject(res)
                }
            },
            fail: (msg) => {
                
                reject(msg)
            },
			complete: ()=>{
				uni.hideLoading()
				// 请求完成，清除当前请求的唯一ID
				manager.deleteById(requestId)
			},
        })
    })
}



const request = {}

const methodsArr = ['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect']

methodsArr.forEach((method) => {
    request[method] = (api, data, loading) => baseRequest(api, method, data, loading)
})

export default request